package com.ksfzhaohui.nio.channels;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.Pipe;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.Random;

public class PipeTest {

	public static void main(String[] args) throws IOException {
		WritableByteChannel out = Channels.newChannel(System.out);

		ReadableByteChannel workerChanel = startWorker(10);
		ByteBuffer buff = ByteBuffer.allocate(100);
		while (workerChanel.read(buff) > 0) {
			buff.flip();
			out.write(buff);
			buff.clear();
		}
	}

	private static ReadableByteChannel startWorker(int reqs) throws IOException {
		Pipe pipe = Pipe.open();
		Worker worker = new Worker(pipe.sink(), reqs);
		worker.start();
		return pipe.source();
	}

	private static class Worker extends Thread {
		private WritableByteChannel channel;
		private int reqs;

		public Worker(WritableByteChannel channel, int reqs) {
			this.channel = channel;
			this.reqs = reqs;
		}

		@Override
		public void run() {
			ByteBuffer buff = ByteBuffer.allocate(100);
			try {
				for (int i = 0; i < this.reqs; i++) {
					doSomework(buff);

					while (channel.write(buff) > 0) {

					}
				}
				this.channel.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		private Random rand = new Random();

		private static String products[] = { "aaaaa", "bbbbb", "ccccc" };

		private void doSomework(ByteBuffer buff) {
			int product = rand.nextInt(products.length);
			buff.clear();
			buff.put(products[product].getBytes());
			buff.put("\r\n".getBytes());
			buff.flip();
		}
	}

}
